#include <jwt.h>
#include <string>
#include <iostream>

extern "C" int sbi_token_init(void);
extern "C" int sbi_token_verify(char *pucToken);

namespace {
	std::string rsa_pub_key = R"(-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuqtJXsmpN+6vCWjQiH19
Nr9ob//zjLn7HB5tV1AYy+j9WiNY6xidQpNbAy4BLv9QedeKuSqjDuzBmimPBHbQ
leTE5pBv0rqoHGUsh/Nl/pIoy9y1g6Y/CfWtGsJp5qooCP+vnuW8m2NF0i+uOsu7
ZB+me4+2dxa5Es9SLYm9XoYqgBYeYfGSO4+/bpZCNWlPJZfGDTI7K5LZJItJ9EB+
j5Z8rZhwpJTlrrG+W9PuGZi8zpSplRLk5C9WABBA9FCjDYN/Qxs9NRrzv4vkOyr8
+IyfIYpvoMGvTZWRjPKnXdwrAegvlTdWMyP/q42Jz9VwuDXJDeoGZ0CI1EaCik4S
9QIDAQAB
-----END PUBLIC KEY-----)";
}
std::string pubkey;
	
int sbi_token_init(void)
{
	char acTmp[70] = {0};
	FILE *pFile = NULL;
	
	pFile = fopen("/disk/upgrade/public.key", "r");
	if (NULL == pFile)
	{
		pubkey = rsa_pub_key;
	}
	else
	{
		while(NULL != fgets(acTmp, sizeof(acTmp), pFile))
		{
			pubkey += acTmp;
			memset(acTmp, 0, sizeof(acTmp));
		}

		/* coverity by wangsq on 2020-11-17 */
		fclose(pFile);
		pFile = NULL;
	}
	
	return 0;
}

int sbi_token_verify(char *pucToken)
{
	try
	{
		auto verify = jwt::verify()
			.allow_algorithm(jwt::algorithm::rs256(pubkey, "", "", ""));

		auto decoded_token = jwt::decode(pucToken);
		
		verify.verify(decoded_token);
	}catch(std::exception& e)
	{
		return -1;
	}
	
	return 0;
}
